package one.stand.controller.index;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.jmp.api.dto.*;
import com.jmp.api.util.LabelUtil;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.DynamicApi;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.*;
import one.stand.enums.LoginEnum;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.DynamicMapperExt;
import one.stand.mapper.UserApiCrmAppMapper;
import one.stand.model.BusinessCard;
import one.stand.model.Dynamic;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.RecordPublicService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.OneStringUtils;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "个人主页")
@RequestMapping("/personal")
@RestController
public class PersonalController {
    @Autowired
    private LiveFeign liveFeign;
    @Autowired
    private DynamicFeign dynamicFeign;
    @Autowired
    private RecordFeign recordFeign;
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private DynamicMapperExt dynamicMapperExt;

    @Autowired
    private UserApiCrmAppMapper userApiCrmAppMapper;

    @ApiOperation(value = "1详情")
    @GetMapping("info")
    @SecurityAuthCheck
    public ResultModel<PersonalInfoResponse> info(@RequestAttribute PersonalInfoRequest request) {

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        UserDto user = userAdminService.get(request.getUserId());
        BusinessCard card = businessCardBaseService.getByUserId(request.getUserId());
        final boolean hasCard = Objects.nonNull(card);
        Company2Dto company2Dto = hasCard ? companyBaseService.get2(card.getCompanyId()) : null;

        int countLeadNum = 0;
        if (hasCard) {
            DynamicListDto dynamicListDto = DynamicListDto.builder()
                    .companyId(company2Dto.getCompanyId())
                    .userId(request.getUserId())
                    .build();
            dynamicListDto.setPageNum(1);
            dynamicListDto.setPageSize(1);
            ResultModel<DynamicListVo> resultModel = dynamicFeign.list(dynamicListDto);
            AssertUtil.isTrue(resultModel);
            countLeadNum = Math.toIntExact(resultModel.getData().getDynamics().getTotal());
        }

        PersonalInfoResponse response = PersonalInfoResponse.builder()
                .userId(user.getUserId())
                .userImg(user.getUserImg())
                .userName(user.getName())

                .countLeadNum(countLeadNum)
                .countFollowNum(recordPublicService.getCollectionCount(RecordPublicService.ITEMTYPE_USER, request.getUserId()))
                .followFlag(BooleanUtils.toInteger(recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_USER, request.getUserId())))

                .userChatId(String.valueOf(user.getUserId()))
                .companyId(hasCard ? card.getCompanyId() : null)
                .companyName(hasCard ? company2Dto.getCompanyName() : null)
                .cardId(hasCard ? card.getCardId() : null)

                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2列表")
    @GetMapping("list")
    @SecurityAuthCheck
    public ResultModel<PersonalListResponse> list(@RequestAttribute PersonalListRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        UserDto user = userAdminService.get(request.getUserId());
        BusinessCard businessCard = businessCardBaseService.getByUserId(request.getUserId());
        String position = Objects.nonNull(businessCard) ? businessCard.getPosition() : null;

        Integer type = ObjectUtil.defaultIfNull(request.getType(), 0);
        AssertUtil.isFalse(type == 3, ResultEnum.VERSION_LOW);

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<PersonalListResponse.Content> contentList = userApiCrmAppMapper.selectPersonalDetail(request.getUserId(), type);
        PageResponse2<PersonalListResponse.Content> contentPageResponse2 = ConvertUtils.page2(contentList, content -> {

            content.setUserImg(user.getUserImg());
            content.setUserName(user.getName());
            content.setPosition(position);

            if (Objects.nonNull(content.getCompanyId())) {
                Company2Dto company2Dto = companyBaseService.get2(content.getCompanyId());
                boolean hasZkgx = companyBaseService.hasZkgx(company2Dto.getCompanyId());
                content.setCompanyName(company2Dto.getCompanyName());
                content.setCompanyLogo(company2Dto.getCompanyLogo());
                content.setCompanyLevel(company2Dto.countCompanyLevelView());
                content.setHasZkgx(BooleanUtils.toInteger(hasZkgx));
            }

            if (content.getType() == 1) {
                ResultModel<LiveInfoResponse> infoResponseResultModel = liveFeign.info(LiveInfoRequest.builder()
                        .roomId(content.getItemId())
                        .build());
                AssertUtil.isTrue(infoResponseResultModel);
                LiveInfoResponse infoResponse = infoResponseResultModel.getData();
                if (!infoResponse.isHasRoom()) {
                    return null;
                }
                if (infoResponse.getLiveStatus() == 2) {
                    content.setType(3);
                    content.setVideo(PersonalListResponse.Video.builder()
                            .roomId(infoResponse.getRoomId())
                            .name(infoResponse.getName())
                            .photo(infoResponse.getPhoto())
                            .videoUrl(infoResponse.getVideoUrl())
                            .userCurrentRoomId(infoResponse.getUserCurrentRoomId())

                            .cardId(businessCard.getCardId())
                            .cardImg(businessCard.getLogo())
                            .cardName(businessCard.getName())
                            .userId(businessCard.getUserId())
                            .userCollectFlag(BooleanUtils.toInteger(recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_USER, businessCard.getUserId())))

                            .viewNum(recordPublicService.getPopularity(SeeRecordEnums.LIVE.getCode(), infoResponse.getRoomId()))
                            .collectNum(recordPublicService.getCollectionCount(RecordPublicService.ITEMTYPE_LIVE_ROOM, infoResponse.getRoomId()))
                            .collectFlag(BooleanUtils.toInteger(recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_LIVE_ROOM, infoResponse.getRoomId())))
                            .commentNum(recordPublicService.countCommentByType(DynamicApi.COMMENT_TYPE_VIDEO, infoResponse.getRoomId()))
                            .build());
                } else {
                    content.setLive(PersonalListResponse.Live.builder()
                            .roomId(infoResponse.getRoomId())
                            .photo(infoResponse.getPhoto())
                            .title(infoResponse.getName())
                            .status(LabelUtil.getLiveStatus(infoResponse.getLiveStatus()))
                            .doThumbsNum(recordPublicService.getCollectionCount(RecordPublicService.ITEMTYPE_LIVE_ROOM, infoResponse.getRoomId()))
                            .build());
                }
            } else if (content.getType() == 2) {
                Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(content.getItemId());
                if (Objects.isNull(dynamic)) {
                    return null;
                }

                boolean isThumbs = recordPublicService.isThumbs(optUser.getUserId(), RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId());
                //最多十条评论
                List<CommentDto> commentDtos = recordPublicService.getCommentList(dynamic.getDynamicId(), 10);
                List<PersonalListResponse.Comment> commentResponseList = ConvertUtils.list(commentDtos, commentModel -> {
                    return PersonalListResponse.Comment.builder()
                            .commentId(commentModel.getCommentId())
                            .userName(commentModel.getUserName())
                            .userLogo(OneStringUtils.photoResize(commentModel.getUserLogo()))
                            .content(commentModel.getText())
                            .userChatId(String.valueOf(commentModel.getUserId()))
                            .time(commentModel.getCreateTime().getTime())
                            .build();
                });

                content.setDynamic(PersonalListResponse.Dynamic.builder()
                        .dynamicId(dynamic.getDynamicId())
                        .photos(dynamic.getPhotos())
                        .title(dynamic.getTitle())
                        .type(dynamic.getType())
                        .userSelfFlag(BooleanUtils.toInteger(dynamic.getCreateUserId().equals(optUser.getUserId())))

                        .commentNum(recordPublicService.countCommentByDynamic(dynamic.getDynamicId()))
                        .doThumbsNum(recordPublicService.getThumbsCount(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId()))
                        .thumbsImgList(ConvertUtils.list(recordPublicService.getThumbsImgs(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId()), thumbsDto -> {
                            return PersonalListResponse.Thumbs.builder()
                                    .userName(thumbsDto.getUserName())
                                    .userChatId(String.valueOf(thumbsDto.getUserId()))
                                    .userImg(OneStringUtils.photoResize(thumbsDto.getUserImg()))
                                    .build();
                        }))
                        .thumbsFlag(BooleanUtils.toInteger(isThumbs))

                        .commentList(commentResponseList)
                        .build());
            }

            return content;
        });

        PersonalListResponse response = PersonalListResponse.builder()
                .contentPage(contentPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2关注个人")
    @PostMapping("/collect")
    @SecurityAuthCheck
    public ResultModel collect(@RequestAttribute PersonalCollectRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<RecordCollectionVo> resultModel = recordFeign.collection(RecordCollectionDto.builder()
                .userId(optUser.getUserId())
                .itemType(RecordPublicService.ITEMTYPE_USER)
                .itemId(request.getUserId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "2分享名片")
    @PostMapping("/share")
    @SecurityAuthCheck
    public ResultModel<PersonalShareResponse> share(@RequestAttribute PersonalCollectRequest request) {
        BusinessCard card = businessCardBaseService.getByUserId(request.getUserId());
        AssertUtil.nonNull(card, ResultEnum.PARAM_CHECK, "名片不存在");

        TemplateGet2Request createRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_CRM_APP_CARD)
                .cardId(card.getCardId())
                .build();
        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(createRequest);
        AssertUtil.isTrue(getResponseResultModel);
        String cardUrl = getResponseResultModel.getData().getImageUrl();

        createRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_WECHAT_CARD)
                .cardId(card.getCardId())
                .build();
        getResponseResultModel = templateFeign.get2(createRequest);
        AssertUtil.isTrue(getResponseResultModel);
        String wechatImgUrl = getResponseResultModel.getData().getImageUrl();

        AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                .companyId(card.getCompanyId())
                .loginEnum(LoginEnum.USER)
                .build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
        String wechatId = accountResponseResultModel.isSuccess() ? accountResponseResultModel.getData().getWechatId() : null;

        PersonalShareResponse response = PersonalShareResponse.builder()
                .wechatId(wechatId)
                .path("/pages/index/main?companyId=" + card.getCompanyId() + "&cardId=" + card.getCardId() + "&goType=1")
                .wechatImgUrl(wechatImgUrl)
                .cardUrl(cardUrl)
                .build();
        return ResultModel.success(response);
    }
}
